{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "1c0eb4ec-f2d1-4a56-9060-2f2cbc88b032",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Setup OpenAI Agent\n",
    "import openai\n",
    "\n",
    "openai.api_key = \"sk-your-api-key\"\n",
    "from llama_index.agent import OpenAIAgent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "22894467-fe82-4d72-8055-f8b79f1dfb3b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load the OpenAPI spec for OpenAI\n",
    "import requests\n",
    "import yaml\n",
    "\n",
    "f = requests.get(\n",
    "    \"https://raw.githubusercontent.com/APIs-guru/openapi-directory/main/APIs/openai.com/1.2.0/openapi.yaml\"\n",
    ").text\n",
    "open_api_spec = yaml.safe_load(f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "33d92b77-5975-4d18-a1e8-15aa028a55f5",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_hub.tools.openapi.base import OpenAPIToolSpec\n",
    "from llama_hub.tools.requests.base import RequestsToolSpec\n",
    "from llama_index.tools.tool_spec.load_and_search.base import LoadAndSearchToolSpec\n",
    "\n",
    "open_spec = OpenAPIToolSpec(open_api_spec)\n",
    "# OR\n",
    "open_spec = OpenAPIToolSpec(\n",
    "    url=\"https://raw.githubusercontent.com/APIs-guru/openapi-directory/main/APIs/openai.com/1.2.0/openapi.yaml\"\n",
    ")\n",
    "\n",
    "requests_spec = RequestsToolSpec(\n",
    "    {\n",
    "        \"api.openai.com\": {\n",
    "            \"Authorization\": \"Bearer sk-your-key\",\n",
    "            \"Content-Type\": \"application/json\",\n",
    "        }\n",
    "    }\n",
    ")\n",
    "\n",
    "# OpenAPI spec is too large for content, wrap the tool to seperate loading and searching\n",
    "wrapped_tools = LoadAndSearchToolSpec.from_defaults(\n",
    "    open_spec.to_tool_list()[0],\n",
    ").to_tool_list()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "009b4690-c8d2-4139-a21c-7ad29e08cc69",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent = OpenAIAgent.from_tools(\n",
    "    [*wrapped_tools, *requests_spec.to_tool_list()], verbose=True\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "d523593f-651c-4d16-ac14-2d08da1e3a76",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=== Calling Function ===\n",
      "Calling function: load_openapi_spec with args: {}\n",
      "Got output: Content loaded! You can now search the information using read_load_openapi_spec\n",
      "========================\n",
      "=== Calling Function ===\n",
      "Calling function: read_load_openapi_spec with args: {\n",
      "  \"query\": \"base url\"\n",
      "}\n",
      "Got output: \n",
      "https://api.openai.com/v1\n",
      "========================\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "Response(response='The base URL for the server is `https://api.openai.com/v1`.', source_nodes=[], metadata=None)"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent.chat(\"what is the base url for the server\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "29c91dff-d9ce-40f4-9e05-31c16da5a9b1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=== Calling Function ===\n",
      "Calling function: read_load_openapi_spec with args: {\n",
      "  \"query\": \"completions api\"\n",
      "}\n",
      "Got output: \n",
      "The OpenAI API provides a completions API which can be accessed using a POST request to the endpoint '/completions'. This API allows users to generate completions for a given prompt.\n",
      "========================\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "Response(response=\"The completions API is an API provided by the OpenAI API. It can be accessed using a POST request to the endpoint '/completions'. This API allows users to generate completions for a given prompt.\", source_nodes=[], metadata=None)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent.chat(\"what is the completions api\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "78edddac-0f6b-4f1e-b0ff-d4cfcc9e1886",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=== Calling Function ===\n",
      "Calling function: post_request with args: {\n",
      "  \"url\": \"https://api.openai.com/v1/completions\"\n",
      "}\n",
      "Got output: {'error': {'message': 'you must provide a model parameter', 'type': 'invalid_request_error', 'param': None, 'code': None}}\n",
      "========================\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "Response(response='To use the completions API and generate a joke, you need to provide a model parameter. Please specify the model you want to use for generating the joke.', source_nodes=[], metadata=None)"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent.chat(\"ask the completions api for a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "ac132a73-7ea9-4ff8-a73a-777d31ee7b7a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=== Calling Function ===\n",
      "Calling function: post_request with args: {\n",
      "  \"url\": \"https://api.openai.com/v1/completions\",\n",
      "  \"data\": {\n",
      "    \"model\": \"text-davinci-003\",\n",
      "    \"prompt\": \"Why don't scientists trust atoms?\",\n",
      "    \"max_tokens\": 50\n",
      "  }\n",
      "}\n",
      "Got output: {'id': 'cmpl-7Yhei5268PoefRhhT47dQgzgmKRg5', 'object': 'text_completion', 'created': 1688505320, 'model': 'text-davinci-003', 'choices': [{'text': '\\n\\nScientists don’t trust atoms because they are considered to be among the most unpredictable of all known sub-atomic particles and can exist in multiple configurations and arrangements, making it difficult for scientists to predict how they will behave in any given situation', 'index': 0, 'logprobs': None, 'finish_reason': 'length'}], 'usage': {'prompt_tokens': 7, 'completion_tokens': 50, 'total_tokens': 57}}\n",
      "========================\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "Response(response=\"Here's a joke for you:\\n\\nWhy don't scientists trust atoms?\\nScientists don’t trust atoms because they are considered to be among the most unpredictable of all known sub-atomic particles and can exist in multiple configurations and arrangements, making it difficult for scientists to predict how they will behave in any given situation.\\n\\nPlease note that this joke was generated using the text-davinci-003 model.\", source_nodes=[], metadata=None)"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent.chat(\"Can you decide the model\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
